<template>
  <div class="qr-management">

    <!-- 查询表单 -->
    <div class="filter-card">
      <div class="card-title">信息管理</div>
      <div class="filter-form">
        <div class="form-item">
          <label>店铺名称：</label>
          <el-input
              v-model="filter.storeName"
              placeholder="请输入店铺名称"
              clearable
          />
        </div>

        <div class="form-item">
          <label>区域类别：</label>
          <el-select
              v-model="filter.regionType"
              placeholder="请选择查询的官方标签"
              clearable
          >
            <el-option
                v-for="item in regionOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>

        <div class="form-actions">
          <el-button @click="resetFilter">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </div>
    </div>

    <!-- 店铺列表 -->
    <div class="list-card">
      <div class="card-title">店铺列表</div>
      <el-table :data="storeList" border style="width: 100%">
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="name" label="门店名称" width="180" />
        <el-table-column prop="address" label="门店地址" />
        <el-table-column prop="storeName" label="店铺名称" width="120" />
        <el-table-column prop="link" label="链接">
          <template #default="{row}">
            <el-tooltip effect="dark" :content="row.link" placement="top">
              <span class="link-text">{{ truncateLink(row.link) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="启用状态" width="120">
          <template #default="{row}">
            <el-switch
                v-model="row.status"
                active-text=""
                inactive-text=""
                align="center"
                @change="toggleStatus(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{row}">
            <el-button
                type="text"
                @click="showQRCode(row)"
            >
              查看二维码
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 二维码弹窗 -->
    <el-dialog
        v-model="qrDialogVisible"
        :title="`${currentStore.name} - 二维码`"
        width="30%"
        center
    >
      <div class="qr-code-container">
        <canvas ref="qrCanvas" class="qr-canvas"></canvas>
      </div>
      <div class="qr-dialog-actions">
        <el-button @click="downloadQRCode">下载二维码</el-button>
        <el-button type="primary" @click="qrDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from 'qrcode';
import axios from 'axios'; // 引入 axios

export default {
  name: 'QRCodeManagement',
  data() {
    return {
      filter: {
        storeName: '',
        regionType: ''
      },
      regionOptions: [
        { value: 'beijing', label: '北京' },
        { value: 'shanghai', label: '上海' },
        { value: 'guangzhou', label: '广州' }
      ],
      storeList: [],
      qrDialogVisible: false,
      currentStore: {}
    };
  },
  methods: {
    truncateLink(link) {
      if (link.length > 30) {
        return link.substring(0, 15) + '...' + link.substring(link.length - 15);
      }
      return link;
    },
    async handleSearch() {
      try {
        const response = await axios.post('http://localhost:8082/api/code/list', {
          ...this.filter
        });
        this.storeList = response.data;
      } catch (error) {
        console.error('查询店铺列表失败:', error);
      }
    },
    resetFilter() {
      this.filter = {
        storeName: '',
        regionType: ''
      };
    },
    async toggleStatus(store) {
      try {
        await axios.post('/api/code/status', {
          id: store.id,
          status: store.status
        });
        console.log('切换店铺状态成功');
      } catch (error) {
        console.error('切换店铺状态失败:', error);
      }
    },
    async showQRCode(store) {
      this.currentStore = store;
      this.qrDialogVisible = true;

      await this.$nextTick();
      try {
        QRCode.toCanvas(this.$refs.qrCanvas, store.link, {
          width: 200,
          margin: 2,
          color: {
            dark: '#000000',
            light: '#ffffff'
          }
        });
      } catch (error) {
        console.error('生成二维码失败:', error);
        this.$message.error('生成二维码失败');
      }
    },
    async downloadQRCode() {
      try {
        const url = await QRCode.toDataURL(this.currentStore.link, {
          width: 400,
          margin: 2
        });
        const link = document.createElement('a');
        link.href = url;
        link.download = `${this.currentStore.name}_二维码.png`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error('下载二维码失败:', error);
        this.$message.error('下载二维码失败');
      }
    }
  },
  mounted() {
    this.handleSearch();
  }
};
</script>

<style scoped>
.qr-management {
  padding: 20px;
  background-color: #f5f7fa;
}

.breadcrumb {
  margin-bottom: 20px;
  font-size: 14px;
  color: #606266;
}

.filter-card, .list-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.form-item {
  flex: 1;
  min-width: 300px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 30px;
}

.link-text {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.qr-code-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.qr-canvas {
  border: 1px solid #ebeef5;
  padding: 10px;
  background: #fff;
}

.qr-dialog-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}
</style>